package com.jzo2o.health.listener;

import cn.hutool.json.JSONUtil;
import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.properties.TradeProperties;
import com.jzo2o.health.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {

    @Autowired
    private TradeProperties tradeProperties;

    @Autowired
    private IOrdersService ordersService;


    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_TRADE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        log.info("接收到支付结果状态的消息 ({})-> {}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);

        //1. 将消息JSON字符串转为消息对象列表
        List<TradeStatusMsg> tradeStatusMsgList = JSONUtil.toList(msg, TradeStatusMsg.class);
        if (CollUtils.isEmpty(tradeStatusMsgList)) {
            return;
        }

        //2. 遍历消息对象列表筛选归属于订单系统的数据并执行更新订单操作
        tradeStatusMsgList.stream()
                .filter(x -> x.getProductAppId().equals(tradeProperties.getProductAppId())
                        && x.getStatusCode().equals(TradingStateEnum.YJS.getCode()))
                .forEach(y -> ordersService.paySuccess(y.getProductOrderNo(), y.getTransactionId(), y.getPaySuccessTime()));


        log.info("[订单状态变更]支付成功状态变更完毕>>>>>>");
    }
}
